<template>
  <t-upload
    v-model="files"
    :placeholder="props.placeholder"
    :theme="props.theme"
    :accept="props.fileType"
    multiple
    :draggable="props.draggable"
    :request-method="uploadFiles"
    :auto-upload="props.autoUpload"
    :max="props.limit"
    :sizeLimit="{
      size: props.fileSize,
      unit: 'MB',
      message: `图片大小不超过 ${props.fileSize} MB`,
    }"
    :before-upload="beforeUpload"
  ></t-upload>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { defineProps, defineEmits, ref } from 'vue';
import AliOssClient from './index';

import $eventBus from '@/utils/eventBus';
import { auditImage } from '@/api/upload';
import { useUserStore } from '@/store';
// import { reject } from 'lodash';

const userStore = useUserStore();
const props = defineProps({
  theme: {
    type: String,
    default: 'image-flow',
  },
  multiple: {
    type: Boolean,
    default: true,
  },
  limit: {
    type: Number,
    defalut: 1,
  },
  With: {
    type: Number,
    default: -1,
  },
  Height: {
    type: Number,
    default: -1,
  },
  fileType: {
    type: String,
    default: 'image/*',
  },
  fileSize: {
    type: Number, //文件大小 以M为单位
    default: 10,
  },
  placeholder: {
    type: String,
    default: '支持批量上传图片文件，注意：上传图片将在24小时内删除',
  },
  draggable: {
    type: Boolean,
    default: true,
  },
  autoUpload: {
    type: Boolean,
    default: false,
  },
  storageDir: {
    type: String,
    default: '',
  },
  storageType: {
    type: String,
    default: 'aliyun',
  },
});

const emit = defineEmits(['uploadSuccess']);

var store: any = null;
const initData = () => {
  return new Promise((resolve, reject) => {
    if (props.storageType === 'aliyun') {
      AliOssClient()
        .then((ret) => {
          //console.log('aliyun oss '+JSON.stringify(ret))
          if(ret)
          {
            store = ret;
            resolve(store);
          }
        })
        .catch((e) => {
          if(e.msg)
          MessagePlugin.error(e.msg)
          reject(e);
        });
    }
    if (props.storageType === 'qiniu') {
      resolve(store);
    }
  });
};

//待传文件
const files = ref([
  // {
  //   url: 'https://tdesign.gtimg.com/demo/demo-image-1.png',
  //   name: 'loading.svg',
  // },
]);

//上传前
const beforeUpload = (file: UploadFile) => {
  if (userStore.userInfo.nick === '') {
    MessagePlugin.error(`请先完成登录`);
    $eventBus.emit('OpenLoginEvent');
    return false;
  }

  const { size } = file;
  if (size / 1024 / 1024 > props.fileSize) {
    MessagePlugin.error(`文件大小受限，不能超过 ${props.fileSize}M`);
    return false;
  }

  //宽高
  console.log('file ' + JSON.stringify(file));
  let reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e) => {
    console.log('reader.onload e', JSON.stringify(e));
    let imgData = e.target.result.split(',')[1];

    if (file.type.indexOf('image') !== -1) {
      //图片审核
      auditImage({
        image_data: imgData,
      })
        .then((ret) => {
          return ret;
        })
        .catch(() => {
          return false;
        });
    } else {
      return true;
    }
  };

  if (store == null) {
    initData();
  }
};
//开始上传
const uploadFiles = async (files: UploadFile | UploadFile[]) => {
  //console.log("uploadFiles " + JSON.stringify(files))

  try {
    let file = files[0];
    let extName = file.name.split('.')[1];
    let key = `${props.storageDir}/${new Date().getTime()}.${extName}`;

    let result = await store.multipartUpload(key, file.raw, {
      progress: function (p: number) {
        file.percent = (p * 100).toFixed(0);
      },
    });

    console.log('result ' + JSON.stringify(result));
    //{"name":"1687177443214.jpg","url":"http://rswl-resource.oss-cn-shanghai.aliyuncs.com/1687177443214.jpg","res":{"status":200,"statusCode":200,"headers":{"content-length":"0","etag":"\"E4221685199DEAC1B7303E40988A3542\"","x-oss-request-id":"649048E30D39F735361A35DD"},"size":0,"aborted":false,"rt":219,"keepAliveSocket":false,"data":{"type":"Buffer","data":[]},"requestUrls":["http://rswl-resource.oss-cn-shanghai.aliyuncs.com/1687177443214.jpg"],"timing":null,"remoteAddress":"","remotePort":""}}
    let res = result.res;
    if (res.status === 200 && res.statusCode === 200) {
      return uploadSuccess(file, result);
    } else {
      return uploadError(result);
    }
  } catch (e) {
    console.log('e', JSON.stringify(e));
    return uploadError(e);
  }
};
//上传成功
const uploadSuccess = (file: any, result: any) => {
  file.percent = 100;
  file.status = 'success';

  console.log('file ' + JSON.stringify(file));
  console.log('upload result ' + JSON.stringify(result));
  let res = {
    status: 'success',
    name: file.name,
    url: file.name,
    size: file.size,
    response: {
      url: result.name,
      files: [{ name: result.name, url: result.name, uploadTime: getCurrentDate(), size: file.size }],
    },
  };

  emit('uploadSuccess', res);

  return new Promise((resolve) => {
    resolve(res);
  });
};
//上传失败
const uploadError = (e: any) => {
  return new Promise((reject) => {
    reject({
      status: 'fail',
      error: '上传出错',
      response: {
        files: [],
      },
    });
  });
};

function getCurrentDate(needTime = false) {
  const d = new Date();
  let month = d.getMonth() + 1;
  month = month < 10 ? `0${month}` : month;
  const date = `${d.getFullYear()}-${month}-${d.getDate()}`;
  const time = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
  if (needTime) return [date, time].join(' ');
  return date;
}
// res.url 图片地址；res.uploadTime 文件上传时间；res.error 上传失败的原因
function formatResponse(res: any) {
  console.log('formatResponse ', JSON.stringify(res));
  // 响应结果添加上传时间字段，用于 UI 显示
  res.uploadTime = getCurrentDate();
  return res;
}

initData();
$eventBus.on('LoginSuccessEvent', () => {
  initData();
});
</script>

<style></style>
